#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

class Student
{
public:
    Student(const char * name, int id)
    : _name(new char[strlen(name) + 1]())
    , _id(id)
    {
        cout << "Student(const char*, int)" << endl;
        strcpy(_name, name);
    }

    void print() const
    {
        cout << "name:" << _name << endl;
        cout << "id:" << _id << endl;
    }

    void destroy()
    {
        //this代表的是当前对象
        delete this;
        //this->~Student();//仅仅调用析构函数还不够
    }

private:
    ~Student()
    {
        cout << "~Student()" << endl;
        if(_name) {
            delete [] _name;
            _name = nullptr;
        }
    }

public:
    //只针对于Student起作用, 其他类型无效
    //重载标准库函数operator new
    void * operator new(size_t sz) {
        cout << "operator new(size_t)" << endl;
        void * pret = malloc(sz);
        return pret;
    }

public:
    //重载标准库函数operator delete
    void operator delete(void * ret) {
        cout << "operator delete(void*)" << endl;
        free(ret);
    }


private:
    char * _name;
    int _id;
};

int main()
{
    //因为Student的数据成员是确定的，那么要申请的空间大小就确定了
    //可以生成堆对象
    Student * pstu = new Student("Jackie", 100);
    pstu->print();

    //问题：堆对象的回收也不能正常进行了
    //delete pstu;//error在类之外调用析构函数
    pstu->destroy();

    //Student stu("Rose", 101);//error，不能生成栈对象
    return 0;
}

